package com.java.struts.order.action;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.java.struts.base.action.BaseAction;
import com.java.struts.order.entity.OrderinfoEntity;
import com.java.struts.order.service.OrderService;
import org.apache.struts2.convention.annotation.Action;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

public class OrderAction extends BaseAction {
    private OrderService orderService = new OrderService();

    private String cart;

    public String getCart() {
        return cart;
    }

    public void setCart(String cart) {
        this.cart = cart;
    }

    @Action(value="listOrder")
    public String listOrder(){
        List<OrderinfoEntity> orders = orderService.listOrders();
        setSuccessResult(orders);
        return "json";
    }

    /**
     * 添加订单
     * @return
     */
    @Action(value = "addOrder")
    public String  addOrder(){

        System.out.println(cart);
        // 将字符串转化为集合
        JSONArray objects = JSONArray.parseArray(cart);
        // 获取当前时间
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        String time = df.format(new Date());// 获取当前系统时间
        //　生成桌号的随机数
        Random random = new Random();
        int Oramadhin = random.nextInt(10);
        System.out.println(cart);
        // 循环遍历集合
        for(int i=0;i<objects.size();i++){
            JSONObject jsonObject = objects.getJSONObject(i);
            // 获取相关信息
            String remark = jsonObject.getString("remark");
            String name = jsonObject.getString("name");
            Float price =Float.parseFloat(jsonObject.getString("price")) ;
            String detail = jsonObject.getString("detail");
            int number =Integer.parseInt(jsonObject.getString("number")) ;
            String sum = jsonObject.getString("sum");
            BigDecimal sumPrice = new BigDecimal(sum);
            int foodid = Integer.parseInt(jsonObject.getString("foodid"));
            // 新建对象
            OrderinfoEntity orderinfo = new OrderinfoEntity();
            orderinfo.setMeid(foodid);
            orderinfo.setOderTime(time);
            orderinfo.setOnote(remark);
            orderinfo.setOnumber(number);
            orderinfo.setOpayment("微信");
            orderinfo.setOramadhin(Oramadhin);
            orderinfo.setOtotal(sumPrice);
            // 调用方法执行添加
            orderService.addOrder(orderinfo);
        }
        return "json";
    }

    public String deleteOrder(){

        return "json";
    }

    public String updateOrder(){

        return "json";
    }

}
